package com.ezlcp.user.config;

import cn.hutool.core.util.RandomUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

/***
 * @description Swagger v3 配置
 * @author Elwin ZHANG
 * @date 2023/1/11 16:58
 */
@Configuration
public class SwaggerConfig {
    //文档标题
    @Value("${springdoc.title:未配置标题}")
    private String title;
    //文档版本
    @Value("${springdoc.version:未配置版本}")
    private String version;
    //文档作者
    @Value("${springdoc.contact.name:未配置作者}")
    private String author;
    //描述
    @Value("${springdoc.description:未配置描述}")
    private String description;

    /**
     * 根据@Tag 上的排序，写入x-order
     * @return the global open api customizer
     */
    @Bean
    public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
        return openApi -> {
            if (openApi.getTags() != null) {
                openApi.getTags().forEach(tag -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("x-order", RandomUtil.randomInt(0, 100));
                    tag.setExtensions(map);
                });
            }
            if (openApi.getPaths() != null) {
                openApi.getPaths().addExtension("x-abb", RandomUtil.randomInt(1, 100));
            }
        };
    }

    /***
     * @description 自定义接口信息
     * @return io.swagger.v3.oas.models.OpenAPI
     * @author Elwin ZHANG
     * @date 2023/1/11 16:58
     */
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title(title)
                        .version(version)
                        .description(description)
                        .contact(new Contact().name(author)));
    }

}
